import {
  ApiCode,
  ApiResult,
  RequestLoginUser,
  RequestUrlEnum,
  ResponseLoginUserInfo
} from '@/config/api_config/api_interface';
import { Method } from 'axios';
import { request } from '@/config/api_config/request';
import { ElMessage } from 'element-plus';
import { router } from '@/config/router_config';
import { RouteNameEnum } from '@/config/router_config/router_components';
import { WindUser } from '@/global';
import { WindAccount } from '@/pages/MainMenu/User/WindAccount/WindAccountList';

/**
 * 统一的请求方法
 * @param urlName 请求地址，只支持enum
 * @param config { data: any, params: any, method: Method } 参数配置
 * @return Promise<ApiResult<T>>
 */
function apiSend<T> (urlName: RequestUrlEnum, config: { data?: any, params?: any, method: Method }) : Promise<ApiResult<T>> {
  return new Promise((resolve, reject) => {
    const req = request({
      method: config.method,
      url: urlName.toString(),
      data: config.data,
      params: config.params
    });
    req.then(res => {
      if ((res.headers['content-type']).includes('application/json')) {
        const data = res.data as ApiResult<T>;
        if (data.apiCode === ApiCode.Success) {
          resolve(data);
        } else if (data.apiCode === ApiCode.NotLogin) {
          ElMessage.error(data.msg as string);
          router.push({ name: RouteNameEnum.login }).then(() => {
            reject(data.msg);
          });
        } else {
          ElMessage.error(data.msg as string);
          resolve(data);
        }
      }
      resolve(res.data as ApiResult<T>);
    }).catch(reason => {
      ElMessage.error(reason);
      reject(reason);
    });
  });
}

/**
 * 登录接口
 * @param loginUser
 */
export function adminLogin (loginUser: RequestLoginUser): Promise<ApiResult<ResponseLoginUserInfo>> {
  return apiSend(RequestUrlEnum.adminLogin, { data: loginUser, method: 'post' });
}

/**
 * 获取系统wind用户列表
 */
export function getWindUserList (): Promise<ApiResult<WindUser[]>> {
  return apiSend(RequestUrlEnum.windUserList, { method: 'post' });
}

export function getWindAccountList (): Promise<ApiResult<WindAccount>> {
  return apiSend(RequestUrlEnum.windAccountList, { method: 'post' });
}
